/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.base;

import picounit.PicoUnitException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class FileReader {
	public byte[] readContents(File file) {
		try {
			InputStream inputStream = new FileInputStream(file);

			byte[] data = new byte[(int) file.length()];

			inputStream.read(data, 0, data.length);

			inputStream.close();

			return data;
		}
		catch (IOException ioException) {
			throw new PicoUnitException(ioException);
		}
	}

	@SuppressWarnings("unchecked")
	public List<String> readLines(File file) throws IOException, FileNotFoundException {
		if (!file.exists()) {
			return Collections.EMPTY_LIST;
		}

		InputStream inputStream = null;

		try {
			inputStream = new FileInputStream(file);

			return new FileReader().readLines(inputStream);
		}
		finally {
			if (inputStream != null) {
				inputStream.close();
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<String> readLines(InputStream inputStream) throws IOException {
		if (inputStream == null) {
			return Collections.EMPTY_LIST;
		}

		List<String> lines = new LinkedList<String>();

		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

		String line = bufferedReader.readLine();

		while (line != null) {
			lines.add(line);

			line = bufferedReader.readLine();
		}

		return lines;
	}
}
